local scheduler = cc.Director:getInstance():getScheduler()
local tryOpenConnectSchId

local ws

---@param cmdObj table
local function cmd(cmdObj)
    local cmdStr = json.encode(cmdObj)
    Log.d("cmd:%s", cmdStr)
    ws:sendString(cmdStr);
end

local function openUrl(url)
    cmd({
        cmd = 'openurl',
        url = url,
    })
end

local function fullscreen(flag)
    cmd({
        cmd = 'fullscreen',
        flag = flag,
    })
end

local function close()
    cmd({
        cmd = 'close'
    })
end

local function test()
    Log.d("wtf:test...")
    openUrl('https://lab.1tai.com')

    close()
end


local function tryOpenConnect()
    Log.d("tryOpenConnect...")

    ws = cc.WebSocket:create("ws://localhost:9999")

    local function WSOpen(strData)
        Log.d("WSOpen")
        scheduler:unscheduleScriptEntry(tryOpenConnectSchId)

        test()
    end

    local function WSMessage(strData)
        Log.d("WSMessage:%s", strData)
    end

    local function WSClose(strData)
        Log.d("WSClose")

        ws = nil
    end

    local function WSError(strData)
        Log.d("WSError: %s", strData)
    end

    -- 注册回调以上的函数
    ws:registerScriptHandler(WSOpen,    cc.WEBSOCKET_OPEN)
    ws:registerScriptHandler(WSMessage, cc.WEBSOCKET_MESSAGE)
    ws:registerScriptHandler(WSClose,   cc.WEBSOCKET_CLOSE)
    ws:registerScriptHandler(WSError,   cc.WEBSOCKET_ERROR)
end

return function()
    tryOpenConnectSchId = scheduler:scheduleScriptFunc(tryOpenConnect, 0.1, false)
end

